﻿module Sustainalytics.Event {

    import Common = Sustainalytics.Common;

    // Home controller
    export class EventListController {
        public eventsTopList: any[];
        // order by column
        public eventsOrderByCol: string;
        // order by direction
        public eventsOrderByColAsc: boolean;
        public lastSkip: number;
        private searchResultsElement;

        ////#region Events listed in calendar
        //public currentUTCDate: Date;
        //// the selected date is used to display the latest events
        //public selectedUtcDate: Date;
        ////used to disabled the calendar next button
        ////public disableNextButton: boolean;
        ////used to disabled the calendar previous button
        //public disablePreviousButton: boolean;
        //// used to display the events filtered by days
        //public daysForSelectedMonth: any[] = new Array;
        ////#endregion Events listed in calendar

        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private EventService: EventService,
            private notificationFactory: Common.INotificationFactory) {

            var ctx = this;

            $scope['eventsList'] = ctx;
            ctx.eventsOrderByCol = 'StartDate';
            ctx.eventsOrderByColAsc = false;
            ctx.eventsTopList = new Array();
            ctx.lastSkip = 0;
            ctx.getEvents();
            ctx.findInDom();
            ctx.addItemsOnScroll();

            //#region events listed in calendar
            //ctx.eventsOrderByCol = 'PublishedDate';
            //ctx.eventsOrderByColAsc = false;

            ////ctx.disableNextButton = true;
            //ctx.disablePreviousButton = false;

            //var date = new Date();
            //ctx.eventsTopList = new Array();

            //ctx.currentUTCDate = ctx.toUTCDate(date);
            //ctx.selectedUtcDate = angular.copy(ctx.currentUTCDate);
            //ctx.getDays();
            //ctx.getEvents();
            //#endregion events listed in calendar
        }

        public getEvents(): ng.IPromise<{}> {
            var ctx = this;
            ctx.$rootScope['loading'] = true;
            ctx.eventsOrderByCol = 'StartDate';
            ctx.eventsOrderByColAsc = false;

            var promiseGet: ng.IPromise<EventDto[]> = ctx.EventService.getEventsList(0, 10, [ctx.eventsOrderByCol], ctx.eventsOrderByColAsc);

            //on success
            promiseGet
                .then(function (lst: any[]) {
                var items = lst['items'];
                if (items) {
                    $(items).each(function () {
                        ctx.eventsTopList.push(this);
                    });
                }
            })
            ['finally'](function () {
                ctx.lastSkip += 10;
                ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        private findInDom() {
            var ctx = this;
            ctx.searchResultsElement = $('#eventsContainer');
        }

        private addItemsOnScroll() {
            var ctx = this;

            // handle scroll
            ctx.searchResultsElement.on('scroll', function (ev) {
                // get scrollbar element
                var target = $(ev.target);

                // check if it reached the max scroll size and go to next page
                if (target[0].scrollHeight == (target.scrollTop() + target.outerHeight())) {
                    ctx.$scope.$apply(function () {

                        ctx.$rootScope['loading'] = true;
                        ctx.eventsOrderByCol = 'StartDate';
                        ctx.eventsOrderByColAsc = false;

                        var promiseGet: ng.IPromise<EventDto[]> = ctx.EventService.getEventsList(ctx.lastSkip, 10, [ctx.eventsOrderByCol], ctx.eventsOrderByColAsc);

                        //on success
                        promiseGet
                            .then(function (lst: any[]) {
                            var items = lst['items'];
                            if (items) {
                                $(items).each(function () {
                                    ctx.eventsTopList.push(this);
                                });
                            }
                        })
                        ['finally'](function () {
                            ctx.lastSkip += 10;
                            ctx.$rootScope['loading'] = false;
                        });
                        return promiseGet;
                    });
                }
            });
        }

        //#region events listed in calendar
        //public toUTCDate = function (date) {
        //    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        //    return _utc;
        //};

        //public getDays() {
        //    var ctx = this; 

        //    ctx.daysForSelectedMonth = new Array();

        //    if (ctx.selectedUtcDate != null) {
        //        var numberDays = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth()+1, 0).getDate();

        //        for (var i = 1; i <= numberDays; i++) {
        //            var newDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth(), i);
        //            ctx.daysForSelectedMonth.push(newDate);
        //        }
        //    }
        //}

        //public getEvents(): ng.IPromise<{}> {
        //    var ctx = this;
        //    ctx.$rootScope['loading'] = true;
        //    ctx.eventsOrderByCol = 'NameLowerCase';
        //    ctx.eventsOrderByColAsc = true;

        //    var startDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth(), 1);
        //    var endDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth()+1, 1);

        //    var promiseGet = ctx.EventService.getEventsList(0, 1000, [ctx.eventsOrderByCol], ctx.eventsOrderByColAsc, startDate, endDate);

        //    //on success
        //    promiseGet
        //        .then(function (lst) {
        //            for (var i in ctx.daysForSelectedMonth) {
        //                ctx.eventsTopList[i] = [];
        //            }
        //            for (var item = 0; item < lst["items"].length; item++) {
        //                    var itemStartDate = new Date((lst["items"][item]).startDate.toString());
        //                    var itemEndDate = new Date((lst["items"][item]).endDate.toString());
        //                    var itemStartDay;
        //                    var itemEndDay;

        //                    if (itemStartDate < startDate && itemEndDate < endDate && startDate < itemEndDate) {
        //                        itemStartDay = 0;
        //                        itemEndDay = itemEndDate.getDate() -1;
        //                    }
        //                    if (itemStartDate < startDate && itemEndDate > endDate && startDate < itemEndDate) {
        //                        itemStartDay = 0;
        //                        itemEndDay = ctx.daysForSelectedMonth.length - 1;
        //                    }
        //                    if (itemStartDate >= startDate && itemEndDate < endDate && startDate < itemEndDate) {
        //                        itemStartDay = itemStartDate.getDate() - 1;
        //                        itemEndDay = itemEndDate.getDate() - 1;
        //                    }
        //                    if (itemStartDate > startDate && itemEndDate > endDate && startDate < itemEndDate) {
        //                        itemStartDay = itemStartDate.getDate() - 1;
        //                        itemEndDay = ctx.daysForSelectedMonth.length - 1;
        //                    }

        //                    for (var add = itemStartDay; add <= itemEndDay; add++) {
        //                        ctx.eventsTopList[add].push(lst["items"][item]);
        //                    }
        //           } 
        //        })
        //        ['finally'](function () {
        //            ctx.$rootScope['loading'] = false;
        //        });
        //    return promiseGet;
        //}

        //public monthDiff(d1, d2) {
        //     var months;
        //     months = (d2.getFullYear() - d1.getFullYear()) * 12;
        //     months -= d1.getMonth();
        //     months += d2.getMonth();
        //     return months <= 0 ? months : months;
        //}

        //public addMonth() {
        //    var ctx = this;
        //    ctx.selectedUtcDate.setMonth(ctx.selectedUtcDate.getMonth() + 1);

        //    var diffMonth = ctx.monthDiff(ctx.currentUTCDate, ctx.selectedUtcDate);

        //    //if (diffMonth >= 0)
        //    //    ctx.disableNextButton = true;
        //    //else
        //    //    ctx.disableNextButton = false;

        //    if (diffMonth <= -2)
        //        ctx.disablePreviousButton = true;
        //    else
        //        ctx.disablePreviousButton = false;

        //    ctx.getDays();
        //    ctx.getEvents();
        //}

        //public decreaseMonth() {
        //    var ctx = this;
        //    ctx.selectedUtcDate.setMonth(ctx.selectedUtcDate.getMonth() - 1);

        //    var diffMonth = ctx.monthDiff(ctx.currentUTCDate, ctx.selectedUtcDate);

        //    //if (diffMonth >= 0)
        //    //    ctx.disableNextButton = true;
        //    //else
        //    //    ctx.disableNextButton = false;

        //    if (diffMonth <= -2 )
        //        ctx.disablePreviousButton = true;
        //    else
        //        ctx.disablePreviousButton = false;

        //    ctx.getDays();
        //    ctx.getEvents();
        //}
        //#endregion  events listed in calendar
    }

    // register controller 
    angular.module('Sustainalytics.Event').controller('EventListController',
        ['$rootScope', '$scope', '$q', '$location', 'EventService', 'notificationFactory', EventListController]);
}  